package com.example.background_service_chengbie

import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

//在 Flutter 引擎下运行的所有 Dart 代码都由一个名为FlutterActivity.
//当这个 Activity 被销毁时，Dart 代码可能不再被执行。

class MainActivity : FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Notifications.createNotificationChannels(this)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        val binaryMessenger = flutterEngine.dartExecutor.binaryMessenger

        //https://developer.android.com/guide/components/activities/process-lifecycle
        MethodChannel(binaryMessenger, "com.example/background_service").apply {
            setMethodCallHandler { method, result ->
                if (method.method == "startService") {
                    val callbackRawHandle = method.arguments as Long
                    BackgroundService.startService(this@MainActivity, callbackRawHandle)
                    result.success(null)
                } else {
                    result.notImplemented()
                }
            }
        }

        //https://developer.android.com/reference/android/app/Activity
        // 将包含此活动的任务移到活动堆栈的后面。任务内的活动顺序不变。
        //如果为 false，则仅当活动是任务的根时才有效；如果为 true，它将适用于任务中的任何活动。
        MethodChannel(binaryMessenger, "com.example/app_retain").apply {
            setMethodCallHandler { method, result ->
                if (method.method == "sendToBackground") {
                    moveTaskToBack(true)
                    result.success(null)
                } else {
                    result.notImplemented()
                }
            }
        }
    }
}
